﻿using AutoMapper;
using PeiYue.IRepository.Base;
using PeiYue.IServices.Sys;
using PeiYue.IServices.Tms;
using PeiYue.Model;
using PeiYue.Model.Dto.Tms;
using PeiYue.Model.ERPModels;
using PeiYue.Model.Models.SM;
using PeiYue.Model.Models.Tms;
using PeiYue.Services.BASE;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PeiYue.Services.Tms
{
    public class TaskHeaderServices : BaseServices<TaskHeaderDao>, ITaskHeaderServices
    {
        IBaseRepository<TaskHeaderDao> _dal;
        IBaseRepository<RouterDao> _routerDal;
        IBaseRepository<VehicleDao> _vehicleDal;
        IBaseRepository<DriverDao> _driverDal;
        IBaseRepository<RouterShopDao> _routerShopDal;
        IBaseRepository<ErpSoHeader> _soHeaderDal;
        IBaseRepository<TaskDetailDao> _taskDetailDal;
        IDicHeaderService _dicServices ;
        IMapper _mapper;
        public TaskHeaderServices(IBaseRepository<TaskHeaderDao> dal,
            IBaseRepository<RouterDao> routerDal,
            IBaseRepository<VehicleDao> vehicleDal,
            IBaseRepository<DriverDao> driverDal,
            IBaseRepository<RouterShopDao> routerShopDal,
            IBaseRepository<ErpSoHeader> soHeaderDal,
            IBaseRepository<TaskDetailDao> taskDetailDal,
            IMapper mapper,
            IDicHeaderService dicServices)
        {
            this._dal = dal;
            base.BaseDal = dal;
            this._routerDal = routerDal;
            this._vehicleDal = vehicleDal;
            this._driverDal = driverDal;
            this._routerShopDal = routerShopDal;
            this._soHeaderDal = soHeaderDal;
            this._taskDetailDal = taskDetailDal;
            this._mapper = mapper;
            this._dicServices = dicServices;
        }
        public async Task<PageModel<SearchTaskHeaderResponseDto>> GetPage(SearchTaskHeaderRequestDto requestDto)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select t.*,u1.namec as create_names,u2.namec as update_names,");
            strSql.Append("r.names as router_name,d.names,d.phones ");
            strSql.Append("from oms_tms_task_header t ");
            strSql.Append("left join oms_ur_user u1 on t.create_user=u1.id ");
            strSql.Append("left join oms_ur_user u2 on t.update_user=u2.id ");
            strSql.Append("left join oms_wms_router r on t.lineid=r.id ");
            strSql.Append("left join oms_wms_driver d on t.driverid=d.id ");
            strSql.Append("where r.status=1 and d.status=1 ");
            List<SugarParameter> parameters = new List<SugarParameter>();
            if (!string.IsNullOrWhiteSpace(requestDto.taskname))
            {
                strSql.Append("and t.taskname like @taskname ");
                parameters.Add(new SugarParameter("@taskname", "%" + requestDto.taskname + "%"));
            }
            if (requestDto.taskstatus.HasValue && requestDto.taskstatus > 0)
            {
                strSql.Append("and t.task_status=@task_status ");
                parameters.Add(new SugarParameter("@task_status", requestDto.taskstatus));
            }
            if (requestDto.router_id.HasValue && requestDto.router_id > 0)
            {
                strSql.Append("and t.lineid=@lineid ");
                parameters.Add(new SugarParameter("@lineid", requestDto.router_id));
            }
            if (!string.IsNullOrWhiteSpace(requestDto.phones))
            {
                strSql.Append("and d.phones like @phones ");
                parameters.Add(new SugarParameter("@phones", "%" + requestDto.phones + "%"));
            }
            if (!string.IsNullOrWhiteSpace(requestDto.names))
            {
                strSql.Append("and d.names like @names ");
                parameters.Add(new SugarParameter("@names", "%" + requestDto.names + "%"));
            }
            if (requestDto.status.HasValue && requestDto.status > 0)
            {
                strSql.Append("and t.status=@status ");
                parameters.Add(new SugarParameter("@status", requestDto.status));
            }
            else
            {
                strSql.Append("and t.status<3 ");
            }
            if (!string.IsNullOrWhiteSpace(requestDto.timef))
            {
                strSql.Append("and t.create_time>=@create_time_begin ");
                parameters.Add(new SugarParameter("@create_time_begin", requestDto.timef));
            }
            if (!string.IsNullOrWhiteSpace(requestDto.timet))
            {
                strSql.Append("and t.create_time<@create_time_end ");
                parameters.Add(new SugarParameter("@create_time_end", Convert.ToDateTime(requestDto.timet).AddDays(1)));
            }
            return await base.SqlQueryPage<SearchTaskHeaderResponseDto>(strSql.ToString(), parameters, requestDto.pageIndex, requestDto.pageSize, " t.id desc ");
        }
        public async Task<(DateTime beginTime, DateTime endTime)> GetOrderLimitTime(int routerType, DateTime now)
        {
            //从字典获取销售正常下单时间段
            var limitBeginTime = (await _dicServices.GetDicDetail("order_limit", "1"))?.v;
            var limitEndTime = (await _dicServices.GetDicDetail("order_limit", "2"))?.v;
            var limitBeginTimeArr = limitBeginTime.Split(':').Select(p => Convert.ToInt32(p)).ToArray();
            var limitEndTimeArr = limitEndTime.Split(':').Select(p => Convert.ToInt32(p)).ToArray();
            var beginDt = now.AddDays(-1);
            var endDt = now;
            DateTime resultBeginTime;
            DateTime resultEndTime;
            if (routerType == 1)
            {
                //正常订单
                resultBeginTime = new DateTime(beginDt.Year, beginDt.Month, beginDt.Day, limitBeginTimeArr[0], limitBeginTimeArr[1], 0);
                resultEndTime = new DateTime(beginDt.Year, beginDt.Month, beginDt.Day, limitEndTimeArr[0], limitEndTimeArr[1], 0);
            }
            else
            {
                //补货订单
                resultBeginTime = new DateTime(beginDt.Year, beginDt.Month, beginDt.Day, limitEndTimeArr[0], limitEndTimeArr[1], 0);
                resultEndTime = new DateTime(endDt.Year, endDt.Month, endDt.Day, limitBeginTimeArr[0], limitBeginTimeArr[1], 0);
            }
            return  (resultBeginTime, resultEndTime);
        }
        /// <summary>
        /// 创建司机任务
        /// </summary>
        /// <param name="ids">线路id</param>
        /// <returns></returns>
        public async Task<MessageModel<string>> CreateTaskBak(List<long> ids)
        {
            var message = new MessageModel<string>();
            RouterDao routerDao = null;
            VehicleDao carDao = null;
            DriverDao driverDao = null;
            TaskHeaderDao taskHeaderDao = null;
            TaskDetailDao taskDetailDao = null;
            List<long> routerShopIdList = new List<long>();
            List<string> shopCodeList = new List<string>();
            List<TaskDetailDao> taskDetailDaoList = null;
            int status = (int)CommonEnum.Status.Enable;
            foreach (var router_id in ids)
            {
                routerDao = (await _routerDal.Query(t => t.id == router_id && t.status == status)).FirstOrDefault();
                if (routerDao == null) continue;
                var tuple = await this.GetOrderLimitTime(routerDao.type, DateTime.Now);
                var beginTime = tuple.beginTime;
                var endTime = tuple.endTime;
                carDao = (await _vehicleDal.Query(t=> t.rt_id == router_id && t.status == status)).FirstOrDefault();
                if (carDao == null)
                {
                    message.status = 500;
                    message.msg=$"线路[{ routerDao.names}]没有关联车辆";
                    return message;
                }
                driverDao = (await _driverDal.Query(t => t.vc_id == carDao.id && t.status == status)).FirstOrDefault();
                if (driverDao == null)
                {
                    message.status = 500;
                    message.msg = $"车辆[{ carDao.names}]没有关联司机";
                    return message;
                }
                taskHeaderDao = (await base.Query(t => t.lineid == router_id && t.create_time > DateTime.Now.Date)).FirstOrDefault();
                if (taskHeaderDao == null)
                {
                    taskHeaderDao = new TaskHeaderDao();
                    taskHeaderDao.lineid = router_id;
                    taskHeaderDao.driverid = driverDao.id;
                    taskHeaderDao.task_status = 1;
                    taskHeaderDao.taskname = $"{DateTime.Now.ToString("yyyyMMdd")}{routerDao.names}配送任务";
                    taskHeaderDao.id =await base.GenId();
                    await base.Add(taskHeaderDao);
                }
                else
                {
                    await base.Update(taskHeaderDao);
                }
                var routerShopList =await _routerShopDal.Query(t => t.router_id == router_id && t.status == status);
                if (routerShopList.Count == 0) continue;
                taskDetailDaoList = new List<TaskDetailDao>();
                foreach (var routerShop in routerShopList)
                {
                    if ((await _taskDetailDal.Query(t=>t.taskid==taskHeaderDao.id && t.shopid== routerShop.shop_id&&t.status== status)).Count>0)
                    {
                        continue;
                    }
                    taskDetailDao = new TaskDetailDao();
                    taskDetailDao.customerid = 0;
                    taskDetailDao.shopid = routerShop.shop_id;
                    taskDetailDao.shop_code = routerShop.shop_code;
                    taskDetailDao.taskid = taskHeaderDao.id;
                    taskDetailDao.task_status = 1;
                    taskDetailDao.expand_time = routerShop.expand_time;
                    taskDetailDao.id = await _taskDetailDal.GenId();
                    taskDetailDaoList.Add(taskDetailDao);
                }
                await _taskDetailDal.Add(taskDetailDaoList);
            }
            message.status = 200;
            message.msg = "创建成功";
            return message;
        }

        public async Task<MessageModel<string>> CreateTask(List<long> ids,long userId)
        {
            var message = new MessageModel<string>();
            if (ids.Count == 0)
            {
                message.status = 500;
                message.msg = "请选择要分配任务的线路";
                return message;
            }
            RouterDao routerDao = null;
            VehicleDao carDao = null;
            DriverDao driverDao = null;
            TaskHeaderDao taskHeaderDao = null;
            TaskDetailDao taskDetailDao = null;
            List<long> routerShopIdList = new List<long>();
            List<string> shopCodeList = new List<string>();
            List<ErpSoHeader> soHeaderList = null;
            List<TaskDetailDao> taskDetailDaoList = null; 
            RouterShopDao routerShopDao = null;
            int status = (int)CommonEnum.Status.Enable;
            var yesterday = DateTime.Now.AddDays(-1).Date;
            var today = DateTime.Now.Date;
            var normalTypeList = new List<string> { "正常订单", "调料订单" };
            var extraTypeList = new List<string> { "上午补货" ,"下午补货","自动订单" };
            foreach (var router_id in ids)
            {
                routerDao = (await _routerDal.Query(t => t.id == router_id && t.status == status)).FirstOrDefault();
                if (routerDao == null) continue;
                var tuple = await this.GetOrderLimitTime(routerDao.type, DateTime.Now);
                var beginTime = tuple.beginTime;
                var endTime = tuple.endTime;
                carDao = (await _vehicleDal.Query(t => t.rt_id == router_id && t.status == status)).FirstOrDefault();
                if (carDao == null)
                {
                    message.status = 500;
                    message.msg = $"[{ routerDao.names}]线路没有关联车辆";
                    return message;
                }
                driverDao = (await _driverDal.Query(t => t.vc_id == carDao.id && t.status == status)).FirstOrDefault();
                if (driverDao == null)
                {
                    message.status = 500;
                    message.msg = $"[{ carDao.names}]车辆没有关联司机";
                    return message;
                }
                var routerShopList = await _routerShopDal.Query(t => t.router_id == router_id && t.status == status);
                if (routerShopList.Count == 0)
                {
                    message.status = 500;
                    message.msg = $"[{ routerDao.names}]线路下没有门店";
                    return message;
                }
                taskHeaderDao = (await base.Query(t => t.lineid == router_id && t.create_time > DateTime.Now.Date)).FirstOrDefault();
                if (taskHeaderDao == null)
                {
                    taskHeaderDao = new TaskHeaderDao();
                    taskHeaderDao.create_user = userId;
                    taskHeaderDao.lineid = router_id;
                    taskHeaderDao.driverid = driverDao.id;
                    taskHeaderDao.task_status = 1;
                    taskHeaderDao.taskname = $"{DateTime.Now.ToString("yyyyMMdd")}{routerDao.names}配送任务";
                    taskHeaderDao.id = await base.GenId();
                    await base.Add(taskHeaderDao);
                }
                else
                {
                    taskHeaderDao.update_user = userId;
                    taskHeaderDao.update_time = DateTime.Now;
                    await base.Update(taskHeaderDao);
                }
                
               
                taskDetailDaoList = new List<TaskDetailDao>();

                foreach (var routerShop in routerShopList)
                {
                    if (taskDetailDaoList.Count > 0 && taskDetailDaoList.Count(t => t.taskid == taskHeaderDao.id && t.shop_code == routerShop.shop_code && t.status == status) > 0)
                        continue;
                    if ((await _taskDetailDal.Query(t => t.taskid == taskHeaderDao.id && t.shop_code == routerShop.shop_code && t.status == status)).Count > 0)
                        continue;
                    if ((await _soHeaderDal.Query(t => t.客户编号 == routerShop.shop_code && t.预计发货 >= DateTime.Now.Date)).Count == 0)
                        continue;
                    taskDetailDao = new TaskDetailDao();
                    taskDetailDao.create_user = userId;
                    taskDetailDao.update_user = userId;
                    taskDetailDao.customerid = 0;
                    taskDetailDao.shopid = routerShop.shop_id;
                    taskDetailDao.shop_code = routerShop.shop_code;
                    taskDetailDao.taskid = taskHeaderDao.id;
                    taskDetailDao.task_status = 1;
                    taskDetailDao.expand_time = routerShop.expand_time;
                    taskDetailDao.id = await _taskDetailDal.GenId();
                    taskDetailDaoList.Add(taskDetailDao);
                }

                //shopCodeList = (await _routerShopDal.Query(t => t.router_id == router_id && t.status == status)).Select(t => t.shop_code).ToList();
                //if (shopCodeList.Count == 0) continue;
                //if (routerDao.type == (int)CommonEnum.RouterType.Normal)
                //{
                //    soHeaderList = await _soHeaderDal.Query(t => t.发货日期 >= today  && normalTypeList.Contains(t.类型) && shopCodeList.Contains(t.客户编号) && t.订单状态 == "待付款");
                //}
                //else
                //{
                //    soHeaderList = await _soHeaderDal.Query(t => t.发货日期>= yesterday && t.发货日期< today &&  extraTypeList.Contains(t.类型) && shopCodeList.Contains(t.客户编号) && t.订单状态 == "待付款");
                //}
                //if (soHeaderList.Count == 0) continue;
                //foreach (var soHeaderDao in soHeaderList)
                //{
                //    routerShopDao = (await _routerShopDal.Query(t => t.router_id == router_id && t.shop_code == soHeaderDao.客户编号 && t.status == status)).FirstOrDefault();
                //    if (routerShopDao == null) continue;
                //    if (taskDetailDaoList.Count > 0 && taskDetailDaoList.Count(t => t.taskid == taskHeaderDao.id && t.shop_code == soHeaderDao.客户编号 && t.status == status) > 0)
                //        continue;
                //    if ((await _taskDetailDal.Query(t => t.taskid == taskHeaderDao.id && t.shop_code == soHeaderDao.客户编号 && t.status == status)).Count > 0)
                //        continue;
                //    taskDetailDao = new TaskDetailDao();
                //    taskDetailDao.create_user = userId;
                //    taskDetailDao.update_user = userId;
                //    taskDetailDao.customerid = 0;
                //    taskDetailDao.shopid = routerShopDao.shop_id;
                //    taskDetailDao.shop_code = soHeaderDao.客户编号;
                //    taskDetailDao.taskid = taskHeaderDao.id;
                //    taskDetailDao.task_status = 1;
                //    taskDetailDao.expand_time = routerShopDao.expand_time;
                //    taskDetailDao.id = await _taskDetailDal.GenId();
                //    taskDetailDaoList.Add(taskDetailDao);
                //}
                if (taskDetailDaoList.Count > 0)
                    await _taskDetailDal.Add(taskDetailDaoList);
            }
            message.status = 200;
            message.success = true;
            message.msg = "创建成功";
            return message;
        }

    }
}
